package obecto.utility
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	
	import mx.utils.StringUtil;
	
	import obecto.core.FLUIComponent;
	import obecto.metadata.PartDirective;
	
	public class PartUtility
	{
		public static function initializePart(
			component : FLUIComponent, view : MovieClip, directive : PartDirective) : DisplayObject 
		{
			var part : DisplayObject = resolvePart(view, directive.path);
			component[directive.name] = part;
			
			return part;
		}
		
		private static function resolvePart(view : MovieClip, path : String) : DisplayObject 
		{
			var segments : Array = path.split(".");
			var clip : MovieClip = view;
			var segment : String;
			
			for (var i : int = 0; i < segments.length; i++)
			{
				segment = segments[i];
				
				if (clip[segment] != null)
				{
					clip = clip[segment];
					continue;
				}
				else
				{
					var currentPath : String = segments.slice(0, i+1).join(".");
					var errorMessage : String = StringUtil.substitute(
						"{0} from {1} is invalid path", currentPath, path);
						
					throw new Error(errorMessage);
				}
			}
			
			return clip;
		}
	}
}